package com.gome.ocean.controller.datasource;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gome.ocean.common.constants.WebSqlContants;
import com.gome.ocean.dao.model.datasource.DataSourceAuthorityOAApplyBean;
import com.gome.ocean.dao.model.datasource.SQLUploadBean;
import com.gome.ocean.dao.model.datasource.SQLUploadRecordBean;
import com.gome.ocean.dao.websql.WebSqlEngine;
import com.gome.ocean.service.base.AuthorityBaseController;
import com.gome.ocean.service.datax.IDataSourceAuthApplyService;
import com.gome.ocean.service.datax.ISQLUploadRecordService;
import com.gome.ocean.service.datax.ISQLUploadService;
import com.google.common.collect.Maps;

/**
 * @author zhangguoqing 2016年10月19日 下午3:23:57/permissionMag/oaCallbackInterface
 * @since 5.0.0
 */
@Controller
@RequestMapping("/permissionMag")
public class OaDBACallBackController extends AuthorityBaseController {

    private static Logger LOG = LoggerFactory.getLogger(OaDBACallBackController.class);

    @Autowired
    private IDataSourceAuthApplyService applyService;
    @Autowired
    private ISQLUploadRecordService     isqlUploadRecordService;
    @Autowired
    private ISQLUploadService           isqlUoloadService;
    @Autowired
    private WebSqlEngine                iEngine;

    @RequestMapping("/oaCallbackInterface")
    @ResponseBody
    public boolean oARecordCallbackInterface(String status, String mainId, String msg) {
        try {
            SQLUploadRecordBean sqlBean = new SQLUploadRecordBean();
            DataSourceAuthorityOAApplyBean applyBean = new DataSourceAuthorityOAApplyBean();
            applyBean.setStatus(Integer.parseInt(status));
            applyBean.setOaMsg(msg);
            applyBean.setId(Long.parseLong(mainId));
            boolean flag = applyService.updateById(applyBean);
            if (flag) {
                Map<String, Object> upMap = Maps.newHashMap();
                upMap.put("ptype", WebSqlContants.SQL_STATUS);
                upMap.put("sn", this.getDiffEnvironmentValue().concat("-") + Long.parseLong(mainId));
                upMap.put("astatus", status);
                String path = WebSqlContants.getFormatAuthorityGroupPathStr(this.getDBAInterfaceIp(),
                    JSON.toJSONString(upMap));
                Map<String, Object> callbackMap = this.executeHttpClientPostUrl(path);
                if (callbackMap.get("state").equals("success")) {
                    sqlBean.setDbaMsg("已告知DBA");
                    sqlBean.setDealStatus(WebSqlContants.STATUS_16);
                    sqlBean.setDealTime(new Date());
                    sqlBean.setCheckStatus(status);
                    sqlBean.setCheckMsg("OA流程已走完!");
                    sqlBean.setCheckTime(new Date());
                    sqlBean.setCreateTime(new Date());
                    sqlBean.setOaDatasourceId(Long.parseLong(mainId));
                } else {
                    sqlBean.setDbaMsg("DBA接口异常,请联系管理员");
                    sqlBean.setOaMsg("id=" + mainId + "DBA接口异常信息为:" + callbackMap.get("info").toString());
                }
                isqlUploadRecordService.insertBean(sqlBean);
                return true;
            }
        } catch (Exception e) {
            LOG.error(e.getMessage());
        }
        return false;
    }

    @RequestMapping(value = "/funDBACallBackInterface")
    @ResponseBody
    public String getDBACallBackInterface(HttpServletRequest request, String params) {
        Map<String, Object> map = Maps.newHashMap();
        try {
            DataSourceAuthorityOAApplyBean applyBean = new DataSourceAuthorityOAApplyBean();
            SQLUploadBean getBean = new SQLUploadBean();
            JSONObject jsonObj = JSON.parseObject(params);
            if (jsonObj != null && jsonObj.size() > 0) {
                String status = jsonObj.get("status").toString();
                if (StringUtils.isEmpty(status)) {
                    map.put("state", "failure");
                    map.put("info", "status 值不能为空");
                    return JSON.toJSONString(map);
                }
                Long mainId = jsonObj.getLong("mainId");
                String msg = jsonObj.get("msg").toString();
                String type = jsonObj.getString("type");
                SQLUploadRecordBean sqlBean = new SQLUploadRecordBean();
                sqlBean.setCreateTime(new Date());
                sqlBean.setDealTime(new Date());
                sqlBean.setDealStatus(status);
                sqlBean.setDbaMsg(msg);
                if (type.equals("sql")) { // SQL提交
                    sqlBean.setSqlUploadId(mainId);
                    getBean.setId(mainId);
                    getBean.setAstatus(status);
                    getBean.setAtime(new Date());
                    getBean.setUpdateTime(new Date());
                    isqlUoloadService.update(getBean);
                } else if (type.equals("db")) { // 权限变更
                    sqlBean.setOaDatasourceId(mainId);
                    applyBean.setStatus(Integer.parseInt(status));
                    applyBean.setDBAMsg(msg);
                    applyBean.setId(mainId);
                    applyBean.setUpdateTime(new Date());
                    applyBean.setCheckTime(new Date());
                    applyService.updateById(applyBean);
                }
                isqlUploadRecordService.insertBean(sqlBean);
                map.put("state", "success");
                map.put("info", "成功");
                return JSON.toJSONString(map);
            }
            map.put("state", "failure");
            map.put("info", "参数 值不能为空");
            return JSON.toJSONString(map);
        } catch (Exception e) {
            LOG.error(e.getMessage());
            map.put("state", "failure");
            map.put("info", "异常信息：" + e.getMessage());
            return JSON.toJSONString(map);
        }
    }

    @RequestMapping(value = "/checkDataUpdateStatusInterface")
    @ResponseBody
    public String checkDataUpdateStatusInterface(HttpServletRequest request, String status, String mainId) {
        try {
            SQLUploadRecordBean sqlBean = new SQLUploadRecordBean();
            Long id = Long.parseLong(mainId);
            sqlBean.setCreateTime(new Date());
            sqlBean.setCheckTime(new Date());
            sqlBean.setSqlUploadId(id);
            sqlBean.setDealStatus(WebSqlContants.STATUS_16);
            sqlBean.setDealTime(new Date());
            Map<String, Object> map = Maps.newHashMap();
            map.put("id", id);
            SQLUploadBean getBean = isqlUoloadService.getBeanByMap(map);

            // 判断是否重复审核
            List<SQLUploadRecordBean> sqlRecLists = isqlUploadRecordService.getBeanListBySqlId(id);
            for (SQLUploadRecordBean rec : sqlRecLists) {
                if (rec.getCountNum() != null) {
                    if (rec.getCountNum() == 1) return "抱歉,审核无效! 您或者您的同事已经成功审核过,请不要重复审核！谢谢!";
                }
            }
            Map<String, Object> inputMap = Maps.newHashMap();
            inputMap.put("ptype", WebSqlContants.SQL_STATUS);
            inputMap.put("sn", this.getDiffEnvironmentValue().concat("-") + id);
            inputMap.put("astatus", status.equals("0") ? WebSqlContants.STATUS_4 : WebSqlContants.STATUS_8);
            String json = JSON.toJSONString(inputMap);
            String path = WebSqlContants.getFormatSQLUploadPathStr(this.getDBAInterfaceIp(), json);
            Map<String, Object> callMap = Maps.newHashMap();
            if (status.equals("0")) { // 不同意
                getBean.setAstatus(WebSqlContants.STATUS_4);
                getBean.setAtime(new Date());
                sqlBean.setCheckStatus(WebSqlContants.STATUS_4);
                sqlBean.setCheckMsg("部门经理邮件审核未批准");
                // 需回调DBA接口告知状态
                callMap = this.executeHttpClientPostUrl(path);
            } else if (status.equals("1")) { // 同意
                getBean.setAstatus(WebSqlContants.STATUS_8);
                getBean.setAtime(new Date());
                sqlBean.setCheckStatus(WebSqlContants.STATUS_8);
                sqlBean.setCheckMsg("审核已批准");
                // 需回调DBA接口告知状态
                callMap = this.executeHttpClientPostUrl(path);
            }
            if (callMap.get("state").equals("success")) {
                sqlBean.setDbaMsg("已告知DBA");
            } else {
                sqlBean.setDbaMsg("DBA接口异常,请联系管理员");
                sqlBean.setOaMsg("id=" + mainId + "DBA接口异常信息为:" + callMap.get("info").toString());
            }
            sqlBean.setCountNum(1L);
            isqlUoloadService.update(getBean);
            isqlUploadRecordService.insertBean(sqlBean);
            return "您好,您已经审核成功,谢谢!";
        } catch (NumberFormatException e) {
            LOG.error(e.getMessage());
            return "发生错误，请告知申请人!" + e.getMessage();
        }
    }

    @RequestMapping(value = "/validDruidDataSource", method = RequestMethod.POST)
    @ResponseBody
    public String validDruidDataSource(String globaConfStr, String appConfStr, String dbPwd) {
        Map<String, Object> map = Maps.newHashMap();
        try {
            if (StringUtils.isBlank(globaConfStr) || StringUtils.isBlank(appConfStr) || StringUtils.isBlank(dbPwd)) {
                map.put("success", false);
                map.put("failure", true);
                map.put("info", "校验参数存在空参数,检查后再调用");
            }
            map = iEngine.vaildateDatasourceByTddlInfo(globaConfStr, appConfStr, dbPwd);
        } catch (Exception e) {
            LOG.error(e.getMessage());
            map.put("success", false);
            map.put("failure", true);
            map.put("info", ExceptionUtils.getMessage(e));
        }
        return JSON.toJSONString(map);
    }

}
